/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ChannelWindow.java
 *
 * Created on 28/08/2009, 9:02:42 AM
 */

package jirc;

import java.io.IOException;
import javax.swing.AbstractListModel;
import javax.swing.JOptionPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLFrameHyperlinkEvent;
import jirc.MainGUI.ServerWithWnd;
import jirc.pircbot.Colors;
import jirc.pircbot.User;

/**
 *
 * @author David
 */
public class ChannelWindow extends javax.swing.JInternalFrame {
	private IRCServer server;
	private String channel;
	private String allTxt = "";

    /** Creates new form ChannelWindow */
    public ChannelWindow(IRCServer server, String channel) {
		setTitle(channel + " on " + server.getServer());
		this.server = server;
		server.joinChannel(channel);
		this.channel = channel;
        initComponents();
		reloadUserList();
    }

	public String getChannel() {
		return channel;
	}

	public IRCServer getServer() {
		return server;
	}

	public void reloadUserList() {
		final User[] users = server.getUsers(channel);
		final String[] userStrs = new String[users.length];
		int count = 0;
		for (User user : users) {
			userStrs[count] = user.getPrefix() + user.getNick();
			count++;
		}
		this.userList.setModel(new AbstractListModel() {
			public int getSize() {
				return userStrs.length;
			}

			public Object getElementAt(int index) {
				return userStrs[index];
			}
		});
	}

	public void dropMessage(String sender, String message) {
		allTxt += "<a href=\"gouser::" + sender + "\">&lt;" + sender + "&gt;</a>&nbsp;" + message + "<br />";
		this.messageDisplay.setText("<html><span style=\"font: 10px 'Arial Bold'\";>" + allTxt + "</span></html>");
		reloadUserList();
	}

	public void dropAction(String sender, String message) {
		allTxt += "* <i><a href=\"gouser::" + sender + "\">" + sender + "<a></i>&nbsp;" + message + "<br />";
		this.messageDisplay.setText("<html><span style=\"font: 10px 'Arial Bold'\"; color:\"red\">" + allTxt + "</span></html>");
		reloadUserList();
	}

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        messageBox = new javax.swing.JTextField();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        userList = new javax.swing.JList();
        jScrollPane1 = new javax.swing.JScrollPane();
        messageDisplay = new javax.swing.JEditorPane();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                closing(evt);
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        messageBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sendMessage(evt);
            }
        });

        jSplitPane1.setDividerLocation(400);

        jScrollPane2.setViewportView(userList);

        jSplitPane1.setRightComponent(jScrollPane2);

        messageDisplay.setContentType("text/html");
        messageDisplay.setEditable(false);
        messageDisplay.addHyperlinkListener(new javax.swing.event.HyperlinkListener() {
            public void hyperlinkUpdate(javax.swing.event.HyperlinkEvent evt) {
                handleLink(evt);
            }
        });
        jScrollPane1.setViewportView(messageDisplay);

        jSplitPane1.setLeftComponent(jScrollPane1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(messageBox, javax.swing.GroupLayout.DEFAULT_SIZE, 538, Short.MAX_VALUE)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 538, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 353, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(messageBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

	private void sendMessage(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendMessage
		final String msg = this.messageBox.getText();
		if (msg.trim().startsWith("/")) {
			String trimMsg = msg.trim();
			String[] cmd = trimMsg.split(" ");
			if (cmd.length >= 2) {
				if (cmd[0].equalsIgnoreCase("/me")) {
					//Action
					StringBuilder action = new StringBuilder();
					for (int i = 1; i < cmd.length; i++) {
						action.append(cmd[i]);
						action.append(" ");
					}
					action.deleteCharAt(action.length() - 1);
					server.sendAction(this.channel, action.toString());
					dropAction(server.getNick(), action.toString());
					return;
				}
			}
		}
		server.sendMessage(channel, Colors.GREEN + msg);
		messageBox.setText("");
		dropMessage(server.getNick(), msg);
	}//GEN-LAST:event_sendMessage

	private void closing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_closing
		int opt = JOptionPane.showConfirmDialog(this, "Do you want to quit the channel?", "Confirmination", JOptionPane.YES_NO_OPTION);
		if (opt == JOptionPane.YES_OPTION) {
			server.partChannel(channel, "Requested (Closing - jIRC)");
			for (ServerWithWnd server_ : Core.mainApp.getServerList()) {
				if (server_.server == this.server) {
					server_.wnd.getChannelWindows().remove(this.channel); //Delete the context
				}
			}
		}
		this.dispose();
	}//GEN-LAST:event_closing

	private void handleLink(javax.swing.event.HyperlinkEvent evt) {//GEN-FIRST:event_handleLink
		if (evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
			System.err.println(evt.getURL().toString());
		}
	}//GEN-LAST:event_handleLink


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTextField messageBox;
    private javax.swing.JEditorPane messageDisplay;
    private javax.swing.JList userList;
    // End of variables declaration//GEN-END:variables

}
